#include "display.h"
#include <TFT_eSPI.h>
#include <math.h>

static const uint16_t screenWidth  = 320;
static const uint16_t screenHeight = 240;
static lv_disp_draw_buf_t draw_buf;
static lv_color_t buf[screenWidth * 10];
static TFT_eSPI tft = TFT_eSPI();

static lv_obj_t* label_status = nullptr;
static lv_obj_t* motor_labels[6];  // 电机角度标签

// 小人腿部线条
static lv_obj_t* line_legL;
static lv_obj_t* line_legR;
static lv_point_t points_legL[4];
static lv_point_t points_legR[4];

// 脚底小圆点
static lv_obj_t* dot_footL;
static lv_obj_t* dot_footR;

// 参数：关节长度
static const int THIGH_LEN = 40;
static const int SHANK_LEN = 40;
static const int FOOT_LEN  = 20;

// 髋关节基准位置
static const int HIP_Y = 100;
static const int HIP_OFFSET_X = 60;  // 左右腿中心点距离屏幕中线的偏移

// 屏幕刷新回调
void my_disp_flush(lv_disp_drv_t* disp, const lv_area_t* area, lv_color_t* color_p) {
    uint32_t w = (area->x2 - area->x1 + 1);
    uint32_t h = (area->y2 - area->y1 + 1);

    tft.startWrite();
    tft.setAddrWindow(area->x1, area->y1, w, h);
    tft.pushColors((uint16_t*)&color_p->full, w * h, true);
    tft.endWrite();
    lv_disp_flush_ready(disp);
}

// 初始化显示
void display_init() {
    lv_init();
    tft.begin();
    tft.setRotation(1);

    lv_disp_draw_buf_init(&draw_buf, buf, NULL, screenWidth * 10);
    static lv_disp_drv_t disp_drv;
    lv_disp_drv_init(&disp_drv);
    disp_drv.hor_res = screenWidth;
    disp_drv.ver_res = screenHeight;
    disp_drv.flush_cb = my_disp_flush;
    disp_drv.draw_buf = &draw_buf;
    lv_disp_drv_register(&disp_drv);

    // 状态标签（顶部居中）
    label_status = lv_label_create(lv_scr_act());
    lv_label_set_text(label_status, "Init...");
    lv_obj_align(label_status, LV_ALIGN_TOP_MID, 0, 0);
    delay(2000);

} 

// 每次循环调用，刷新 LVGL
void display_loop() {
    lv_timer_handler();
    delay(5);
}

// 更新状态文字
void display_set_status(const char* text) {
    if (label_status) {
        lv_label_set_text(label_status, text);
    }
}

